Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

188
Visualizações
I have two input elements with class "inputWithLimit". Why would both be firing simultaneously and logging '0' as val().length?
$(document).ready(function() {
    $(".inputWithLimit").each(() => {
        var inp = this;
        inp.addEventListener("input",
            function (event){
                console.log($(inp).val().length);
            });
    });
})

I've also tried "keyup" and "change" as event handlers, and in both other cases, jquery is doing a strange thing with assigning these listeners. Thanks.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

If you are using jQuery then there is no need to loop through each element and add an event listener. An example which logs the value of each input when you input something.

$(document).ready(function() {
    $(".inputWithLimit").on('input',function() {
        console.log(this.value);
    });
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="inputWithLimit">
<input class="inputWithLimit">

about 4 years ago · Juan Pablo Isaza Relatório

0

The problem is your arrow function. When using arrow function, then you can't use `this'

$(".inputWithLimit").on("input", function() {
  console.log($(this).val().length);
});

I've also made your code shorter.

Demo

$(document).ready(function() {
  $(".inputWithLimit").on("input", function() {
    console.log($(this).val().length);
  });
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="inputWithLimit" />

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda